//
//  ChatConversationViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/17.
//

#import "ChatConversationViewController.h"
#import "ChatInfoViewController.h"
#import "GroupInfoViewController.h"
#import "GroupSelectMemberViewController.h"
#import "RoomInfoViewController.h"
#import <YMCallKit/LocalRendererView.h>

@interface ChatConversationViewController ()<YMWebRTCClientDelegate>
@property (nonatomic,strong)UIButton *moreBtn;
@property (nonatomic, strong) YMWebRTCClient *rtcClient;
@property (nonatomic, strong) NSMutableDictionary <NSString *, RTCVideoTrack *> *remoteVideoTracks; /**< 远程的视频追踪 */
@property (nonatomic, strong) RTCVideoTrack *localVideoTrack; /**< 本地摄像头追踪 */
@property (nonatomic, strong) RTCVideoTrack *remoteTrack; /**< 远程摄像头追踪 */
@property (nonatomic,strong) LocalRendererView *localView;
@property (nonatomic,strong)NSMutableArray *userArray;

@end

@implementation ChatConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userArray = [NSMutableArray array];
    [self.chatInputBarControl.pluginBoardView insertItem:[UIImage imageNamed:@"YMIM.bundle/voip/plugin_item_video"] highlightedImage:[UIImage imageNamed:@"YMIM.bundle/voip/plugin_item_video_highlighted"] title:@"视频通话" tag:1111];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.moreBtn];
    self.navigationItem.rightBarButtonItem = right;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(singleHangUp) name:@"singleHangUp" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatRefuse) name:@"chatRefuse" object:nil];
    
}

-(void)moreAction{
    
    if (self.conversationType == ConversationType_PRIVATE) {
        
        ChatInfoViewController *vc = [[ChatInfoViewController alloc]init];
        NSArray *array = [self.conversation valueForKey:@"userList"];
        YMUserInfo *info = array[0];
        vc.tid = info.userId;
        vc.targetId = self.targetId;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (self.conversationType == ConversationType_GROUP){
        
        GroupInfoViewController *vc = [[GroupInfoViewController alloc]init];
        vc.groupId = self.targetId;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (self.conversationType == ConversationType_CHATROOM){
        
        RoomInfoViewController *vc = [[RoomInfoViewController alloc]init];
        vc.roomId = self.targetId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.rtcClient leaveChannel];
    
}
- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:[UIImage imageNamed:@"Friend_More"] forState:UIControlStateNormal];
        _moreBtn.frame = CGRectMake(0, 0, 40, 40);
        [_moreBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}
#pragma mark - hook
- (void)pluginBoardView:(YMPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag {
    [super pluginBoardView:pluginBoardView clickedItemWithTag:tag];
    NSLog(@"tag:%ld",tag);
    if (tag == 1111) {
        
        if (self.conversationType == ConversationType_PRIVATE) {
            
            [self beginVideo];//单人
            
        }else if (self.conversationType == ConversationType_GROUP||self.conversationType == ConversationType_CHATROOM){

            GroupSelectMemberViewController *vc = [[GroupSelectMemberViewController alloc]init];
            vc.groupId = self.targetId;
            [vc setDidSelectResultBlock:^(NSArray<NSString *> * _Nonnull userArray) {
                
                
                NSString *userId = [YMIMClient sharedClient].userInfo.userId;
                NSString *userName = [YMIMClient sharedClient].userInfo.userName;
                NSString *userAvatar = [YMIMClient sharedClient].userInfo.userAvatar;
                
                NSMutableArray *arr = [NSMutableArray array];
                for (int i = 0; i<userArray.count; i++) {
                    
                    YMFriendInfo *userInfo = userArray[i];
                    CallUser *info = [[CallUser alloc]init];
                    info.uid = userInfo.friendId;
                    info.username = userInfo.friendName;
                    info.userAvatar = userInfo.friendAvatar;
                    if ([userId isEqualToString:info.uid]) {
                        
                        [arr removeObject:info];
                        
                    }else{
                        
                        [arr addObject:info];
                    }
                    
                }
                self.userArray = arr;
                
                CallUser *userInfo = [CallUser new];
                userInfo.userAvatar = userAvatar;
                userInfo.username = userName;
                userInfo.uid = userId;
                [self.userArray addObject:userInfo];
                
                [[YMCallManager shared]callMutil:self.userArray userName:userInfo.username userAvatar:userInfo.userAvatar channelId:self.targetId];   //多人
                
                            
            }];
            [self.navigationController pushViewController:vc animated:YES];

        }
       
    }
}


//- (void)openDynamicFunction:(NSInteger)functionTag {
//    NSLog(@"tag:%ld",functionTag);
//    if (functionTag == 1111) {
//
//        if (self.conversationType == ConversationType_PRIVATE) {
//
//            [self beginVideo];//单人
//
//        }else if (self.conversationType == ConversationType_GROUP){
//
//            GroupChatViewController *vc = [[GroupChatViewController alloc]init];
//            vc.groupId = self.targetId;
//            [vc setDidSelectResultBlock:^(NSArray<NSString *> * _Nonnull userArray) {
//
//
//                NSString *userId = [YMIMClient sharedClient].userInfo.userId;
//                NSString *userName = [YMIMClient sharedClient].userInfo.userName;
//                NSString *userAvatar = [YMIMClient sharedClient].userInfo.userAvatar;
//
//                NSMutableArray *arr = [NSMutableArray array];
//                for (int i = 0; i<userArray.count; i++) {
//
//                    YMFriendInfo *userInfo = userArray[i];
//                    CallUser *info = [[CallUser alloc]init];
//                    info.uid = userInfo.friendId;
//                    info.username = userInfo.friendName;
//                    info.userAvatar = userInfo.friendAvatar;
//                    if ([userId isEqualToString:info.uid]) {
//
//                        [arr removeObject:info];
//
//                    }else{
//
//                        [arr addObject:info];
//                    }
//
//                }
//                self.userArray = arr;
//
//                CallUser *userInfo = [CallUser new];
//                userInfo.userAvatar = userAvatar;
//                userInfo.username = userName;
//                userInfo.uid = userId;
//                [self.userArray addObject:userInfo];
//
//                [[YMCallManager shared]callMutil:self.userArray userName:userInfo.username userAvatar:userInfo.userAvatar channelId:self.targetId];   //多人
//
//
//            }];
//            [self.navigationController pushViewController:vc animated:YES];
//
//        }
//
//    }
//
//}

- (void)beginVideo {
    //发送点对点消息
    YMConversation *conversation = self.conversation;
    NSArray  *userList = conversation.userList;

    NSString *toUserId = [self valueForKey:@"toUserId"];
    YMUserInfo *info = userList[0];
    [[YMCallManager shared]callUser:toUserId userName:info.userName userAvatar:info.userAvatar channelId:self.targetId];

}

#pragma  mark 收到对方挂断电话
-(void)singleHangUp{
    
    [self.localView removeFromSuperview];
    //    [self.rtcClient leaveChannel];
    //    self.rtcClient.delegate = nil;
    
    
}
#pragma  mark 收到对方取消
-(void)chatRefuse{
    
    [self.localView removeFromSuperview];
    [self.localView stopSound];
    
}
#pragma mark - WebRTCClientDelegate
- (void)webRTCClient:(YMWebRTCClient *)webRTCClient setLocalStream:(RTCMediaStream *)stream {
    
    self.localVideoTrack = [stream.videoTracks lastObject];
    self.localView.localRenderer.videoContentMode = UIViewContentModeScaleAspectFill;
    [self.localVideoTrack addRenderer:self.localView.localRenderer];
    
}

- (void)webRTCClient:(YMWebRTCClient *)webRTChelper addRemoteStream:(RTCMediaStream *)stream connectionID:(NSString *)connectionID
{
    [self.remoteVideoTracks setObject:[stream.videoTracks lastObject] forKey:connectionID];
    self.remoteTrack = [self.remoteVideoTracks valueForKey:connectionID];
    [self.remoteTrack addRenderer:self.localView.remoteRenderer];
    
}

- (void)webRTCClient:(YMWebRTCClient *)webRTChelper removeConnection:(NSString *)connectionID
{
    [self.remoteVideoTracks removeObjectForKey:connectionID];
}

- (NSMutableDictionary<NSString *,RTCVideoTrack *> *)remoteVideoTracks {
    if (!_remoteVideoTracks) {
        _remoteVideoTracks = [[NSMutableDictionary alloc] init];
    }
    return _remoteVideoTracks;
}


@end
